//
//  CountButton.swift
//  LeMessage
//
//  Created by Rowling on 2020/3/9.
//  Copyright © 2020 Rowling. All rights reserved.
//

import UIKit
import RxSwift
class CountButton: UIButton {
      private let obervabel = Observable<Int>.timer(.seconds(0), period: .seconds(1), scheduler: MainScheduler.instance)
      var second = 0
      @IBInspectable var format : String = "%ldS"
    
      private var dispose : Disposable?
    
      @IBInspectable var disAbleBgColor : UIColor?
      @IBInspectable var disAnabelTitleColor : UIColor?
    
      var normalBgColor : UIColor!
      var normalTitleColor : UIColor! // 正常情况下的字体颜色
     /**正常展示*/
     var normalStr = ""
      override func awakeFromNib() {
          super.awakeFromNib()
          normalStr = titleLabel!.text!
          normalBgColor = backgroundColor
          normalTitleColor = titleLabel?.textColor
      }
      
      private func countOn() {
          dispose = obervabel.takeUntil(self.rx.deallocated).subscribe({[weak self] (e) in
              guard let self = self else {return}
              print(self.second)
              self.setTitle(String(format: self.format, self.second), for: .normal)
//              self.sizeToFit()
              if self.second == 0 {
                  self.second = 0
                  self.isEnabled = true
                  self.backgroundColor = self.normalBgColor
                  self.setTitle(self.normalStr, for: .normal)
                  if let d = self.dispose {
                      d.dispose()
                  }
              }
              self.second -= 1
          })
      }
      
      //MARK:--------------------开始计时--------------------
      func start(time:Int) {
          normalStr = titleLabel!.text!
          second = time
          isEnabled = false
          backgroundColor = disAbleBgColor ?? normalBgColor
          countOn()
      }
      
    override var isEnabled: Bool {
        set {
            if second > 0 {
                super.isEnabled = false
            } else {
                super.isEnabled = newValue
            }
            if super.isEnabled {
                backgroundColor =  normalBgColor
                setTitleColor(normalTitleColor, for: .normal)
            } else {
                backgroundColor = disAbleBgColor ?? normalBgColor
                if let disAbelTitleColor = disAnabelTitleColor {
                    setTitleColor(disAbelTitleColor, for: .normal)
                }
            }
        }
        
        get {
            super.isEnabled
        }
    }
    
      deinit {
          print("over")
      }
}
